package com.ybear.ybutils.utils.design

import androidx.core.util.Consumer

abstract class AbsLogger {
    var loggerId: Long = 0
    var nextLogger: AbsLogger? = null
    private var endCall: Consumer<Long>? = null

    constructor()

    constructor(loggerId: Long) {
        this.loggerId = loggerId
    }

    constructor(loggerId: Long, nextLogger: AbsLogger?) {
        this.loggerId = loggerId
        this.nextLogger = nextLogger
    }

    constructor(loggerId: Long, nextLogger: AbsLogger?, endCall: Consumer<Long>?) {
        this.loggerId = loggerId
        this.nextLogger = nextLogger
        this.endCall = endCall
    }


    override fun toString(): String {
        return "AbsLogger{" +
                "loggerId=" + loggerId +
                ", nextLogger=" + nextLogger +
                ", endCall=" + endCall +
                '}'
    }



    fun runLogger() {
        //处理结束后拦截下一个Logger
        if (write()) {
            checkFinish()
            return
        }
        nextLogger()
    }

    internal fun nextLogger() {
        if (nextLogger != null) nextLogger!!.runLogger()
        checkFinish()
    }

    private fun checkFinish() {
        //链路处理完毕
        if (nextLogger != null && endCall != null) endCall!!.accept(loggerId)
    }

    fun setLoggerEndFinishCall(endCall: Consumer<Long>?) {
        this.endCall = endCall
    }

    /**
     * 处理的内容
     * @return    false:处理完调度下一个logger, true:拦截下一个logger, 等待nextLogger 主动触发
     */
    abstract fun write(): Boolean
}